package com.lhg.common.exception;

import com.lhg.common.page.ResultInfo;
import com.lhg.common.util.JsonUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyExceptionResolver implements HandlerExceptionResolver {

    private static Logger logger = Logger.getLogger(MyExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        response.setContentType("text/html;charset=UTF-8");//处理响应编码
        ex.printStackTrace();
        logger.error(ex.getMessage(), ex);
        BusinessException businessException = null;
        //向前台返回错误信息
        try {
            if (ex instanceof BusinessException) {
                businessException = (BusinessException) ex;
            } else {
                businessException = new BusinessException("系统错误，请与管理员联系");
            }
            response.getWriter().print(JsonUtil.toJson(ResultInfo.fail(businessException.getMessage())));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}